package com.li.drug.controller;

import com.li.drug.service.UserService;
import com.li.drug.utils.ResultMapUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 用户相关controller
 */
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    /**
     * 判断用户是否登录成功
     * @return
     */
    @RequestMapping("/toLogin")
    @ResponseBody
    public Object toLogin(String username,String password){

//        if(username==null||password==null){
//            return ResultMapUtil.getHashMapLogin("用户名密码不能为空","2");
//        }
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户信息
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        try{
            subject.login(token); //执行登录操作,如果没有异常就登录成功
            return ResultMapUtil.getHashMapLogin("登录成功","1");
        }catch (UnknownAccountException e){
            return ResultMapUtil.getHashMapLogin("用户名不存在","2");
        }catch (IncorrectCredentialsException e){
            return ResultMapUtil.getHashMapLogin("密码错误","2");
        }
    }

    /**
     * 转向后台首页
     * @return
     */
    @RequestMapping("/index")
    public String index(){
        return "index";
    }

    /**
     * 退出登录
     * @return
     */
    @RequestMapping("/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login";
    }

    /**
     * 欢迎页面
     * @return
     */
    @RequestMapping("/welcome")
    public String welcome(){
        return "welcome";
    }
}
